package de.busschedule.view;

import java.io.IOException;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.database.SQLException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import de.busschedule.R;
import de.busschedule.control.DBHandler;
import de.busschedule.control.TabsPagerAdapter;
import de.busschedule.logging.Logger;

public class LineListActivity extends FragmentActivity implements TabListener{
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    //Tab titles
    private String[] tabs = {"City Bus", "Regional Bus", "Night Bus"};
	
	private final String TAG = "LineListActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_linelist);
		
		//Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
 
        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);       
 
        //Adding Tabs
        for(String tab_name : tabs){
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }
        
        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                // on changing the page select respective tab 
                actionBar.setSelectedNavigationItem(position);
            }
         
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2){}
         
            @Override
            public void onPageScrollStateChanged(int arg0){}
        });

		//Open the database
		DBHandler handler = new DBHandler(this);
		try{
			handler.createDataBase();
		}catch(IOException e){
			Logger.error(TAG, "Could not create database!");
		}
		try{
			handler.openDataBase();
		}catch(SQLException sqle){
			Logger.error(TAG, "Could not open database!");
			throw sqle;
		}
	}
	
	@Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
 
    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected show respective fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }
 
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
}
